/**
 * 
 */
package com.idea.zd.sys.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.idea.zd.sys.model.Admin;
import com.idea.zd.sys.model.Permission;
import com.idea.zd.sys.service.AdminService;
import com.idea.zd.sys.service.PermissionService;
import com.jfinal.kit.StrKit;

/**
 * @author y.z
 */
public class DbRealm extends AuthorizingRealm {

		private AdminService adminService = new AdminService();
		
		private PermissionService permissionService = new PermissionService();
		
		  
		/**
	     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	     */
	    @Override
	    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	    	Subject currentUser = SecurityUtils.getSubject(); 
    		Session session = currentUser.getSession();
    		Admin admin = (Admin) session.getAttribute("admin");
    		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    		
    		if(null != admin){
    			List<Permission> perList = permissionService.getAllPermissionList(admin);
    			
    			for(Permission p:perList){

					info.addStringPermission(p.getStr("visit_url"));
    			}
    			
    			
    		}
	    	return info;
	    	

	    	/*String userName = (String) getAvailablePrincipal(principals);
	    	  //通过用户名去获得用户的所有资源，并把资源存入info中
	    	  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	    	  Set<String> s = new HashSet<String>();
	    	  s.add("p1");  
	    	  s.add("p2"); 
	    	  info.setStringPermissions(s);
	    	  Set<String> r = new HashSet<String>();
	    	  r.add("r1"); 
	    	  r.add("r2"); 
	    	  info.setRoles(r);
	    	  return info;*/
	    }

	    /**
	     * 认证回调函数,登录时调用.
	     */ 
	    @Override
	    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
	            throws AuthenticationException {

	    	UsernamePasswordToken authcToken = (UsernamePasswordToken) token;  

	    	//验证用户名
	        String username = authcToken.getUsername();
	        
	        if (StrKit.isBlank(username)) {
	            throw new AuthenticationException("用户名不可以为空");
	        }
	        
	        //验证用户是否存在
	        Admin user = adminService.getByUserAccount(username);
	        
	        if(user==null){
	        	throw new UnknownAccountException("用户不存在!");
	        }else{
	        	//验证密码
	        	String password = String.valueOf(authcToken.getPassword());
	        	PasswordService svc = new DefaultPasswordService();
	        	
	        	if(svc.passwordsMatch(password, svc.encryptPassword(user.getStr("password")))){
	        		Subject currentUser = SecurityUtils.getSubject(); 
	        		Session session = currentUser.getSession();
	        		session.setAttribute("admin",user);
	        		return  new SimpleAuthenticationInfo(new SimpleUser(user.getStr("id"), user.getStr("account"),user.getStr("name"),user.getStr("email")), password, getName());
	        	}else{
	        		throw new AuthenticationException("密码错误!");
	        	}
	        }
	    }


}
